package com.xy.modular.basics.service.impl;

import com.xy.modular.basics.dao.UserAuthLocalMapper;
import com.xy.modular.basics.dao.UserMapper;
import com.xy.modular.basics.entity.user.User;
import com.xy.modular.basics.entity.user.UserAuthLocal;
import com.xy.modular.basics.service.IShiroService;
import com.xy.modular.sys.dao.RoleMapper;
import com.xy.modular.sys.entity.role.Role;
import com.xy.shiro.ShiroUser;
import org.apache.shiro.authc.CredentialsException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service("shiroService")
@Transactional(readOnly = true)
public class IShiroServiceImpl implements IShiroService {

	@Resource
	private UserMapper userMapper;

	@Resource
	private UserAuthLocalMapper userAuthLocalMapper;

	@Resource
	private RoleMapper roleMapper;

	//@Autowired
	//private PermissionsMapper permissionMapper;

	@Override
	public UserAuthLocal getUserAuths(String principal) {
		UserAuthLocal userAuthLocal = userAuthLocalMapper.getByIdentifier(principal);
		// 账号不存在
		if (null == userAuthLocal) {
			throw new CredentialsException();
		}
		return userAuthLocalMapper.getByIdentifier(principal);
	}

	@Override
	public ShiroUser shiroUser(UserAuthLocal userAuths) {
		User user = userMapper.getById(userAuths.getAuthId());
		ShiroUser shiroUser = new ShiroUser();

		shiroUser.setId(user.getId());
		shiroUser.setName(user.getName()); // 用户名称
		shiroUser.setRealName(user.getRealName());
		List<Role> roles = roleMapper.getRole(user.getId());
		for (Role role : roles) {
			//role.setPermissions(permissionMapper.getPermission(role.getId()));
		}
		shiroUser.setRoleList(roles);
		return shiroUser;
	}

	@Override
	public List<String> findPermissionsByRoleId(Integer roleId) {
		return null;
	}

	@Override
	public String findRoleNameByRoleId(Integer roleId) {
		return null;
	}

	/*
	 * @Override public SimpleAuthenticationInfo info(ShiroUser shiroUser, User
	 * user, String realmName) { String credentials = user.getPassword(); // 密码加盐处理
	 * String source = user.getSalt(); ByteSource credentialsSalt = new
	 * Md5Hash(source); return new SimpleAuthenticationInfo(shiroUser, credentials,
	 * credentialsSalt, realmName); }
	 */

}
